package com.chj.design.producerconsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumer3 {
	private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();

//	https://juejin.cn/post/6844903602469732360#heading-4
	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(15);
		for (int i = 0; i < 2; i++) {
			service.submit(new Productor(queue));
		}
		for (int i = 0; i < 4; i++) {
			service.submit(new Consumer(queue));
		}
	}

	static class Productor implements Runnable {

		private BlockingQueue<Integer> queue;

		public Productor(BlockingQueue<Integer> queue) {
			this.queue = queue;
		}

		@Override
		public void run() {
			try {
//				while (true) {
				for (int i = 0; i < 5; i++) {
					Thread.sleep(500);
					Random random = new Random();
					int ri = random.nextInt();
					System.out.println("生产者: " + Thread.currentThread().getName() + ", 生产数据: " + ri);
					queue.put(ri);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	static class Consumer implements Runnable {
		private BlockingQueue<Integer> queue;

		public Consumer(BlockingQueue<Integer> queue) {
			this.queue = queue;
		}

		@Override
		public void run() {
			try {
//				while (true) {
				for (int i = 0; i < 10; i++) {
					Thread.sleep(700);
					Integer element = (Integer) queue.take();
					System.out.println("消费者: " + Thread.currentThread().getName() + ", 正在消费数据: " + element);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}